package com.itheima.ThreadTest.first;

import org.junit.jupiter.api.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadTest {
    @Test
    public void testThread() {
        Thread thread = new MyThread("");
        thread.start();
        for (int i = 0; i < 6; i++) {
            System.out.println("主："+i);
        }
    }

    @Test
    public void testThread2() {
        Runnable myRunnable = new MyRunnable();
        new Thread(myRunnable).start();
        for (int i = 0; i < 6; i++) {
            System.out.println("主："+i);
        }
    }

    @Test
    public void testThread3() { // 可以简写成这样
        Runnable myRunnable = new MyRunnable();
        new Thread(()->{
            for (int i = 0; i < 6; i++) {
                System.out.println("线程 ："+i);
            }
        }).start();
        for (int i = 0; i < 6; i++) {
            System.out.println("主："+i);
        }
    }

    @Test
    public void testCallable() throws ExecutionException, InterruptedException {
        Callable<String> call = new MyCallable(100);
        FutureTask<String> futureTask = new FutureTask<>(call);
        new Thread(futureTask).start();
        // 代码执行到这里如果线程没执行完会等待
        String result = futureTask.get();
        System.out.println(result);
    }

    @Test
    public void testThreadFun() throws InterruptedException {
        Thread t1 = new MyThread("1号名字");
        t1.setName("1号线程");
        t1.start();
        t1.join(); // t1 跑完
        System.out.println(t1.getName());

        Thread t2 = new MyThread("2号名字");
        t2.start();
        // 获取当前线程对象
        Thread m = Thread.currentThread();
        System.out.println(m.getName());
        for (int i = 0; i < 6; i++) {
            System.out.println("main:"+i);
        }
    }
}
